<!--
 * @Author: hongbin
 * @Date: 2021-10-11 07:11:55
 * @LastEditTime: 2021-10-11 14:30:12
 * @Description: 用canvas实现键盘输入文字效果
 * @FilePath: /undefined/Users/hongbin/Code/JavaScript/demo/canvas欢迎文字.html
-->
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        canvas {
            border: 1px solid #000;
        }
    </style>
</head>

<body>
    <canvas id="canvas">
        canvas都显示不了求求你换个现代的浏览器吧
    </canvas>

    <script>
        const canvasWidth = 400;
        const canvasHeight = 400;
        const canvas = document.getElementById('canvas');
        canvas.width = canvasWidth;
        canvas.height = canvasHeight;
        const ctx = canvas.getContext("2d");

        ctx.clearRect(0, 0, canvasWidth, canvasHeight);

        const str = '一二三四五六七八九十';
        const startSpot = [20, 100];//开始点
        const currentSpot = [...startSpot];//记录当前的坐标
        const fontSize = 20;//字体

        const drawText = (text, x, y) => {
            ctx.beginPath();
            ctx.font = `${fontSize}px 微软雅黑`;
            ctx.fillStyle = "#000";
            ctx.textBaseline = "top";
            ctx.fillText(text, x, y);
            ctx.closePath();
        }

        const drawVerticalLine = (x, start, end) => {
            ctx.beginPath();
            ctx.moveTo(x, start);
            ctx.lineTo(x, end);
            ctx.strokeStyle = '#000';
            ctx.stroke();
            ctx.closePath();
        }

        let index = 0;//画到第几个字符了
        const space = 500;

        function draw() {
            const char = str[index++];
            //清除上一条插入点
            ctx.clearRect(currentSpot[0] + 9, currentSpot[1], 2, fontSize);
            if (!char) return;
            console.log(char);
            drawText(char, ...currentSpot);//画一个文字
            currentSpot[0] += 20;//绘画点向右移动一个字符的距离
            drawVerticalLine(currentSpot[0] + 10, currentSpot[1], currentSpot[1] + fontSize);
            setTimeout(() => draw(), space);
        }

        setTimeout(() => draw(), space)

    </script>
</body>

</html>